package com.wust.dns_resolver.service;

import com.wust.dns_resolver.utils.DnsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.IOException;


@Service
@Slf4j
public class DnsServiceImpl implements DnsService {


    @Override
    public String getIpAddress(String domainName, boolean isIPv6) {
        String ipAddress = "";
        
        log.info("当前解析的域名为: {}, 解析类型: {}", domainName, isIPv6 ? "IPv6" : "IPv4");

        // 验证域名格式
        if (!DnsUtils.isValidDomain(domainName)) {
            log.info("错误：无效的域名格式!");
            return "错误：无效的域名格式!";
        }

        // 构建DNS查询报文
        byte[] query = DnsUtils.buildQuery(domainName, isIPv6);

        // 打印查询报文
        log.info("发送的DNS查询报文：");
        DnsUtils.printPacket(query);

        // 发送查询并接收响应
        byte[] response = new byte[0];
        try {
            response = DnsUtils.sendAndReceive(query);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 打印响应报文
        log.info("接收的DNS查询报文：");
        DnsUtils.printPacket(response);

        // 解析响应
        ipAddress = DnsUtils.parseResponse(response, isIPv6);

        return ipAddress;
    }
}
